package com.hh.base.util.file;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by liuhanhui on 2017/10/27.
 */
public class FileUtil {

    public static void writeFile(String path, String content) throws IOException {
        File file = new File(path);
        if (!file.exists()) {
            file.getParentFile().mkdir();
        }
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(content.getBytes());
        fileOutputStream.close();
    }

    public static String readFile(String path) throws IOException {
        File file = new File(path);
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
        String tempString;
        StringBuilder content = new StringBuilder("");
        while ((tempString = bufferedReader.readLine()) != null) {
            content.append(tempString + "\n");
        }
        bufferedReader.close();
        return content.toString();
    }

    public static String readClassFile(Class<?> clazz, String path) throws IOException {
        path = clazz.getResource(path).getPath();
        return readFile(path);
    }

    public static boolean createDir(String destDirName) {
        File dir = new File(destDirName);
        if (dir.exists()) {
            System.out.println("创建目录" + destDirName + "失败，目标目录已经存在");
            return false;
        }
        if (!destDirName.endsWith(File.separator)) {
            destDirName = destDirName + File.separator;
        }
        //创建目录
        if (dir.mkdirs()) {
            System.out.println("创建目录" + destDirName + "成功！");
            return true;
        } else {
            System.out.println("创建目录" + destDirName + "失败！");
            return false;
        }
    }

    public static List<File> getClassFileList(Class<?> clazz, String filePath) {
        return getFileList(clazz.getResource(filePath).getPath(), null);
    }

    private static List<File> getFileList(String strPath, List<File> filelist) {
        if (filelist == null) {
            filelist = new ArrayList<File>();
        }
        File dir = new File(strPath);
        File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                String fileName = files[i].getName();
                if (files[i].isDirectory()) { // 判断是文件还是文件夹
                    getFileList(files[i].getAbsolutePath(), filelist); // 获取文件绝对路径
                } else { // 判断文件名是否以.avi结尾
                    String strFileName = files[i].getAbsolutePath();
                    filelist.add(files[i]);
                }
            }

        }
        return filelist;
    }


}
